package com.base.po.coupon_sdk;

import com.base.utils.Md5Encrypt;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

public class CouponUtil {

    /**
     * 参数拼接
     */
    public static String getParam(Map<String, String> paramsMap, String sign){
        List<String> params = new ArrayList<>();
        for(String key : paramsMap.keySet()){
            params.add(key + "=" + paramsMap.get(key));
        }

        // 返回拼接参数
        String param = "";
        try{
            for (int i = 0; i < params.size(); i++){
                if (i == 0){
                    param += params.get(i);
                }else {
                    param += "&" + params.get(i);
                }
            }
        }catch (Exception e){
            param = "";
        }
        // 参数不为空 拼接sign
        if (param != null && !param.equals("") && sign != null && !sign.equals("")){
            param += "&sign=" + sign;
        }else {
            param = "";
        }
        return param;
    }

    /**
     * 生成签名
     */
    public static String getSign(Map<String, String> paramsMap, String tradeKey){
        List<String> params = new ArrayList<>();
        for(String key : paramsMap.keySet()){
            params.add(key + paramsMap.get(key));
        }

        // 返回MD5签名
        String sign = "";
        //String.CASE_INSENSITIVE_ORDER A在 a 前面
        Collections.sort(params, String.CASE_INSENSITIVE_ORDER);
        // 获取拼接参数
        String param = "";
        try{
            for (int i = 0; i < params.size(); i++){
                param += params.get(i);
            }
        }catch (Exception e){
            return sign;
        }
        // 参数不为空 拼接key
        if (param != null && !param.equals("") && tradeKey != null && !tradeKey.equals("")){
            param += tradeKey;
        }else{
            return sign;
        }
        // MD5加密
        try {
            sign = Md5Encrypt.encrypt32(param);
        } catch (Exception e) {
            return sign;
        }
        return sign;
    }
}
